﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
using Gw2Api;

namespace Gw2WvWMapControl
{
    public class ObjectiveDisplayConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (null == value)
                return "";
            return ObjectiveDisplayToText(value as WvWObjectiveDisplay);
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        private string ObjectiveDisplayToText(WvWObjectiveDisplay obj)
        {
            TimeSpan time = (new TimeSpan(0, 5, 0) - (DateTime.UtcNow - obj.ts));
            TimeSpan timeHeld = DateTime.UtcNow - obj.ts;
            string guildString = (!string.IsNullOrEmpty(obj.owner_guild) ? "\nClaimed by " + obj.owner_guild : "" );
            string timeString = (time.TotalSeconds >= 0 ? "\nRI ends in " + time.ToString(@"m\:ss") : "\nHeld for " + FormatTimeSpan(timeHeld));
            ObjectiveUpgradeDetails upgrade = obj.upgrade_details;
            string upgradeString = "\nTier " + upgrade.CurrentTierId + (upgrade.NextTier != null ? " (" + upgrade.CurrentTierYaks + "/" + upgrade.NextTier.yaks_required + " yaks)" : "");
            upgradeString += " | " + obj.points_tick + " Points per Tick";
            return obj.name + " | " + obj.owner_world + " (" + obj.owner + ")" + guildString + timeString + upgradeString;
        }

        private string FormatTimeSpan(TimeSpan time)
        {
            List<string> formats = new List<string>();
            if (time.Minutes >= 1 && time.Minutes < 2)
            {
                formats.Add("m' minute'");
            }
            else if (time.Minutes >= 2)
            {
                formats.Add("m' minutes'");
            }
            if (time.Hours >= 1 && time.Hours < 2)
            {
                formats.Add("h' hour'");
            }
            else if (time.Hours >= 2)
            {
                formats.Add("h' hours'");
            }
            if (time.Days >= 1 && time.Days < 2)
            {
                formats.Add("d' day'");
            }
            else if (time.Days >= 2)
            {
                formats.Add("d' days'");
            }

            formats.Reverse();

            string format = String.Join("', '", formats);

            return time.ToString(format);
        }
    }
}
